package cn.highedu.http;

import java.io.File;
import java.time.LocalDateTime;

/**
 * 封装请求处理功能
 */
public class DispatcherServlet {
    private static File root;
    private static File staticDir;
    static {
        //初始化静态资源路径， 用于加载静态资源
        try {
            root = new File(
                    DispatcherServlet.class.getClassLoader().getResource(".").toURI()
            );
            staticDir = new File(root, "static");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private static DispatcherServlet instance = new DispatcherServlet();

    private DispatcherServlet(){
    }
    public static DispatcherServlet getInstance() {
        return instance;
    }

    /**
     * 处理请求过程，根据请求的URI，找到对应文件
     * @param request 解析好请求信息
     * @param response 向客户端发送的信息
     */
    public void service(HttpServletRequest request,
                        HttpServletResponse response){
        //String uri = request.getUri();
        String path = request.getRequestURI();
        if ("/submit".equals(path)) {
            String name = request.getParameter("name");
            String gender = request.getParameter("gender");
            //动态生成网页内容
            String html = "<html>" +
                    "<body>" +
                    "收到参数：" + name + ", " + gender + "<br>" +
                    LocalDateTime.now().toString() +
                    "</body>" +
                    "</html>";
            response.setContent(html);
        }else if ("/register".equals(path)){
            String name = request.getParameter("name");
            String gender = request.getParameter("gender");
            //动态生成网页内容
            String html = "<html>" +
                    "<body>" +
                    "收到注册：" + name + ", "+ gender + "<br>" +
                    LocalDateTime.now().toString()+
                    "</body>" +
                    "</html>";
            response.setContent(html);
        }else {
            File file = new File(staticDir, path);
            if (file.isFile()) {
                response.setContentFile(file);
            } else {
                File errorPage = new File(staticDir, "404.html");
                response.setStatusCode(404);
                response.setStatusReason("Not Found");
                response.setContentFile(errorPage);
            }
        }
    }
}
